const app = getApp();
const codeApi = require('../../../utils/codeApi.js');

Page({
  data: {
    codeInput: '',
    userId: '',
    nickname: '',
    remainingCount: '',
    totalCount: '',
    activationStatus: '',
    activationTime: '',
    isLoading: false
  },

  onInputChange(e) {
    this.setData({
      codeInput: e.detail.value
    });
  },

  async onSearch() {
    const code = this.data.codeInput.trim();
    if (!code) {
      wx.showToast({ 
        title: '请输入激活码', 
        icon: 'none',
        duration: 2000
      });
      return;
    }

    this.setData({ isLoading: true });

    try {
      codeApi.queryCode({ codeNum: code }).then(res => {
        this.setData({ isLoading: false });
        
        if (res.code === 0) {
          const codeData = res.data.code || {};
          const userData = res.data.user || null;

          // 格式化激活时间
          const formatTime = (timeStr) => {
            if (!timeStr || timeStr === 'null') return '未激活';
            try {
              const date = new Date(timeStr);
              return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
              });
            } catch (e) {
              return timeStr;
            }
          };

          this.setData({
            userId: userData ? userData.id : '',
            nickname: userData ? userData.nickname : '',
            remainingCount: userData ? userData.remainingCount : '',
            totalCount: codeData.totalCount || '0',
            activationStatus: this.mapStatus(codeData.status),
            activationTime: formatTime(codeData.used_at)
          });

          // 显示查询成功提示
          wx.showToast({
            title: '查询成功',
            icon: 'success',
            duration: 1500
          });
        } else {
          // 清空之前的查询结果
          this.clearData();
          wx.showToast({ 
            title: res.message || '查询失败', 
            icon: 'none',
            duration: 2000
          });
        }
      }).catch(err => {
        this.setData({ isLoading: false });
        this.clearData();
        console.error('查询失败:', err);
        wx.showToast({ 
          title: '网络错误，请稍后重试', 
          icon: 'none',
          duration: 2000
        });
      });
    } catch (err) {
      this.setData({ isLoading: false });
      this.clearData();
      console.error('查询异常:', err);
      wx.showToast({ 
        title: '查询失败，请稍后重试', 
        icon: 'none',
        duration: 2000
      });
    }
  },

  // 清空查询结果
  clearData() {
    this.setData({
      userId: '',
      nickname: '',
      remainingCount: '',
      totalCount: '',
      activationStatus: '',
      activationTime: ''
    });
  },

  // 状态映射
  mapStatus(status) {
    switch (status) {
      case 0: return '未激活';
      case 1: return '已激活';
      case 2: return '已过期';
      default: return '未知';
    }
  },

  // 页面加载时清空数据
  onLoad() {
    this.clearData();
  },

  // 页面显示时重置输入框焦点
  onShow() {
    // 可以在这里添加一些页面显示时的逻辑
  }
});
